#include <iostream>
using namespace std;

#include <pthread.h>
#include <unistd.h>

/* 读写锁 */
pthread_rwlock_t g_rwlock;
/* 全局数据 */
int g_cnt = 100;

void *thread_func1(void *arg)
{
    while (1)
    {
        /* 加锁(读锁) */
        pthread_rwlock_rdlock(&g_rwlock);
        cout << "hello" << endl;
        sleep(10);
        printf("thread1 thread Id:%lu, g_cnt:%d\n", pthread_self(), g_cnt);
        /* 解锁 */
        pthread_rwlock_unlock(&g_rwlock);
    }
    /* 退出线程 */
    pthread_exit(NULL);
}

void *thread_func2(void *arg)
{
    sleep(100);
    while (1)
    {
        /* 加锁(读锁) */
        pthread_rwlock_rdlock(&g_rwlock);
        printf("thread2 thread Id:%lu, g_cnt:%d\n", pthread_self(), g_cnt);
        /* 解锁 */
        pthread_rwlock_unlock(&g_rwlock);
        usleep(100);
    }

    /* 退出线程 */
    pthread_exit(NULL);
}

void *thread_func3(void *arg)
{
    usleep(100);
    while (1)
    {
        /* 加锁(写锁) */
        pthread_rwlock_wrlock(&g_rwlock);
        g_cnt += 66;
        printf("thread3 thread Id:%lu,g_cnt = %d\n", pthread_self(), g_cnt);
        pthread_rwlock_unlock(&g_rwlock);
    }

    /* 退出线程 */
    pthread_exit(NULL);
}

void *thread_func4(void *arg)
{
    /* 退出线程 */
    pthread_exit(NULL);
}

int main()
{
    /* 初始化读写锁 */
    pthread_rwlock_init(&g_rwlock, NULL);

    pthread_t tid1;
    pthread_create(&tid1, NULL, thread_func1, NULL);
    pthread_t tid2;
    pthread_create(&tid2, NULL, thread_func1, NULL);
    pthread_t tid3;
    pthread_create(&tid3, NULL, thread_func1, NULL);
    pthread_t tid4;
    pthread_create(&tid4, NULL, thread_func1, NULL);

    while (1)
    {
        sleep(1);
    }
    /* 销毁读写锁 */
    pthread_rwlock_destroy(&g_rwlock);
    return 0;
}